/**
 * 
 */
package components;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreePath;

public class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor
{

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -7672153425386391314L;

	CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();

	ChangeEvent changeEvent = null;

	JTree tree;

	public CheckBoxNodeEditor(JTree tree)
	{
		this.tree = tree;
	}

	public Object getCellEditorValue()
	{
		JCheckBox checkbox = this.renderer.getLeafRenderer();
		CheckBoxNode checkBoxNode = new CheckBoxNode(checkbox.getText(), checkbox.isSelected());
		return checkBoxNode;
		// return new CheckBoxNode("axx", true);
	}

	public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected,
	        boolean expanded, boolean leaf, int row)
	{

		// Component editor = this.renderer.getTreeCellRendererComponent(tree, value, true,
		// expanded,
		// leaf, row, true);
		//
		// // editor always selected / focused
		// ItemListener itemListener = new ItemListener()
		// {
		// public void itemStateChanged(ItemEvent itemEvent)
		// {
		// if (CheckBoxNodeEditor.this.stopCellEditing())
		// {
		// CheckBoxNodeEditor.this.fireEditingStopped();
		// }
		// }
		// };
		// if (editor instanceof JCheckBox)
		// {
		// ((JCheckBox) editor).addItemListener(itemListener);
		// }
		//
		// return editor;
		return new JCheckBox("xxx");
	}

	public boolean isCellEditable(EventObject event)
	{
		boolean returnValue = false;
		if (event instanceof MouseEvent)
		{
			MouseEvent mouseEvent = (MouseEvent) event;
			TreePath path = this.tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
			if (path != null)
			{
				Object node = path.getLastPathComponent();
				if ((node != null) && (node instanceof DefaultMutableTreeNode))
				{
					DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
					Object userObject = treeNode.getUserObject();
					returnValue = ((treeNode.isLeaf()) && (userObject instanceof CheckBoxNode));
				}
			}
		}
		return returnValue;
	}
}
